#include <iostream>

using namespace std;

//c++编译器至少给一个类添加4个函数
//1.默认构造函数(无参，函数体为空)
//2.默认析构函数(无参，函数体为空)
//3.默认拷贝构造函数，对属性进行值拷贝
//4.赋值运算符 operator=,对属性进行值拷贝

//如果类中有属性指向堆区，做赋值操作时也会出现深浅拷贝问题

//赋值运算符重载
class Person {
public:
    int *age;

    Person() {

    }

    Person(int age) {
        this->age = new int(age);
    }

    ~Person() {
        if (age != nullptr) {
            delete age;
            age = nullptr;
        }
    }

    //赋值运算符重载
    Person &operator=(Person &person) {
        //编译器默认提供浅拷贝
        //this->age=age;
        //应该先判断是否有属性在堆区，如果有先释放干净，然后再深拷贝
        if (age != nullptr) {
            delete age;
            age = nullptr;
        }
        this->age = new int(*person.age);
        return *this;
    }
};

void test1() {
    Person person1(18);
    Person person2(20);
    Person person3(30);
    person3 = person2 = person1;//赋值运算
    cout << "person1:age=" << *person1.age << endl;
    cout << "person2:age=" << *person2.age << endl;
    cout << "person3:age=" << *person3.age << endl;
}

int main() {
    test1();
    return 0;
}
